const multer = require('multer');
const fs  = require('fs');
const {env}  = require('../config');
const {logger}  = require('./log');
const moment = require('dayjs');
// const { v4: uuid } = require("uuid");
// const { nanoid: uuid } = require("nanoid");
const { md5 } = require("./md5");
const { replaceAll } = require("./str");

const TYPE_IMAGE = {
  'image/png' : 'png',
  'image/jpeg': 'jpeg',
  'image/jpg' : 'jpg'
};
exports.imgUpload =
  multer({
    limits: {
      files: 5,
      filesize: 512 * 1024, // 512K
    },
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        const path = env.UPLOAD.PATH + 'img' + moment().format('/YYYYMM/DD/');
        if ( !fs.existsSync(path) ) {
          fs.mkdirSync(path, { recursive: true});
        }
        cb(null, path);
      }
    }),
    fileFilter: (req, file, cb) => {
      let size = +req.rawHeaders.slice(-1)[0]
      let isValid = false;
      if (!!TYPE_IMAGE[file.mimetype] && size < 4 * 1024 * 1024) {
        isValid = true
      }
      let error = isValid ? null : new Error('Invalid img mime type!');
      cb(error, isValid);
    }
  });

  // + newpath newname renamefile
  // TODO 压缩 multiFile
exports.afterUpload = function (file) {
  // typeof file == '[array]'
  // "fieldname": "avatar",
  //   "originalname": "404.jpg",
  //     "encoding": "7bit",
  //       "mimetype": "image/jpeg",
  //         "destination": "public/uploads/img/202109/20/",
  //           "filename": "0ee541a12431abb448f68a142baecdc4",
  //             "path": "public\\uploads\\img\\202109\\20\\0ee541a12431abb448f68a142baecdc4",
  //               "size": 62151
  const ext = TYPE_IMAGE[file.mimetype];
  const newname = md5(fs.readFileSync(file.path).toString()) + '.' + ext;
  // console.log('after', file, newname);
  const newpath = file.destination + newname
  file.newname  = newname
  file.newpath  = newpath
  fs.access(newpath,err => {
    logger.info('after upload ' + JSON.stringify(err))
    // 异步需要 logger 打印到文件
    if(err){ // 不存在 => path => newpath
      fs.renameSync(file.path, newpath)
    }else{ // 存在 => 删除path
      fs.unlinkSync(file.path)
    }
  });
}
const TYPE_File = {
  'application/pdf': 'pdf',
};
exports.fileUpload =
  multer({
    limits: {
      files: 5,
      filesize: 2024 * 1024, // 2M
    },
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        const path = env.UPLOAD.PATH + 'file'+ moment().format('/YYYYMM/DD/');
        // console.log('multer --' , path );
        if (!fs.existsSync(path)) {
          fs.mkdirSync(path, { recursive: true });
        }
        cb(null, path);
      },
    }),
    fileFilter: (req, file, cb) => {
      let size = +req.rawHeaders.slice(-1)[0]
      let isValid = false;
      if (!!TYPE_File[file.mimetype] && size < 1 * 1024 * 1024) {
        isValid = true
      }
      let error = isValid ? null : new Error('Invalid file mime type!');
      cb(error, isValid);
    }
  });